package it.fuesi.bubblekids.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import it.fuesi.bubblekids.R;


/**
 * Created by pascotto on 10/11/14.
 */
public class ColorPreference extends Preference implements SeekBar.OnSeekBarChangeListener {

    private static final String TAG = "ColorPreference";

    private ImageView mBgPreview;
    private SeekBar mColorR;
    private SeekBar mColorG;
    private SeekBar mColorB;
    private TextView mColorHex;

    private String mHex;
    private int mR;
    private int mG;
    private int mB;


    public ColorPreference(Context context){
        super(context);
    }

    public ColorPreference(Context context, AttributeSet attrs){
        super(context, attrs);
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);

        Log.d(TAG, "OnBindView");

        mBgPreview = (ImageView)view.findViewById(R.id.color_preview);
        mColorHex = (TextView)view.findViewById(R.id.color_hex);
        mColorR = (SeekBar)view.findViewById(R.id.color_R);
        mColorR.setOnSeekBarChangeListener(this);
        mColorG = (SeekBar)view.findViewById(R.id.color_G);
        mColorG.setOnSeekBarChangeListener(this);
        mColorB = (SeekBar)view.findViewById(R.id.color_B);
        mColorB.setOnSeekBarChangeListener(this);

        mColorR.setProgress(mR);
        mColorG.setProgress(mG);
        mColorB.setProgress(mB);


    }



    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
        changeBgColorPreview(seekBar);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        changeBgColorPreview(seekBar);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    public static String toHex(int r, int g, int b){
        return r + "-" + g + "-" + b;
    }

    public static int[] fromHex(String hex){
        final int[] array = new int[3];
        final String[] s = hex != null ? hex.split("[-]") : new String[0];
        if(s.length != 3){
            array[0] = 0;
            array[1] = 0;
            array[2] = 0;
        }else {
            array[0] = Integer.parseInt(s[0]);
            array[1] = Integer.parseInt(s[1]);
            array[2] = Integer.parseInt(s[2]);
        }
        return array;
    }


    private void changeBgColorPreview(SeekBar seekBar){
        Log.d(TAG, "changeBgColorPreview");

        if(seekBar.getId() == R.id.color_R)
            mR = seekBar.getProgress();

        if(seekBar.getId() == R.id.color_G)
            mG = seekBar.getProgress();

        if(seekBar.getId() == R.id.color_B)
            mB = seekBar.getProgress();

        mHex = toHex(mR, mG, mB);


        Log.d(TAG, "changeBgColorPreview --> preview width["+mBgPreview.getWidth()+"] - height["+mBgPreview.getHeight()+"]");

        //if(mBgPreview.getWidth() > 0 && mBgPreview.getHeight() > 0){
            Bitmap mBitmap = Bitmap.createBitmap(300, 300,
                    Bitmap.Config.ARGB_8888);

            Canvas c = new Canvas(mBitmap);

            c.drawColor(Color.argb(255, mR, mG, mB));

            mBgPreview.setImageBitmap(mBitmap);

       // }



        mColorHex.setText(mHex);

        persistString(mHex);


    }

    @Override
    protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
        if (restorePersistedValue) {
            // Restore existing state
            mHex = this.getPersistedString("0-0-0");
        } else {
            // Set default state from the XML attribute
            mHex = (String) defaultValue;
        }

        Log.d(TAG, "onSetInitialValue --> " + mHex);

        if(mHex != null && !mHex.isEmpty()) {

            mR = fromHex(mHex)[0];
            mG = fromHex(mHex)[1];
            mB = fromHex(mHex)[2];

        }


    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Log.d(TAG, "onSaveInstanceState");
        final Parcelable superState = super.onSaveInstanceState();
        // Check whether this Preference is persistent (continually saved)
        if (isPersistent()) {
            // No need to save instance state since it's persistent,
            // use superclass state
            return superState;
        }

        // Create instance of custom BaseSavedState
        final SavedState myState = new SavedState(superState);
        // Set the state's value with the class member that holds current
        // setting value
        Log.d(TAG, "onSaveInstanceState --> " + mHex);

        myState.value = mHex;
        return myState;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        Log.d(TAG, "onRestoreInstanceState");
        // Check whether we saved the state in onSaveInstanceState
        if (state == null || !state.getClass().equals(SavedState.class)) {
            // Didn't save the state, so call superclass
            super.onRestoreInstanceState(state);
            return;
        }

        // Cast state to custom BaseSavedState and pass to superclass
        SavedState myState = (SavedState) state;
        super.onRestoreInstanceState(myState.getSuperState());

        // Set this Preference's widget to reflect the restored state

        Log.d(TAG, "onRestoreInstanceState --> " + myState.value);

        if(myState.value != null && !myState.value.isEmpty()) {

            mR = fromHex(mHex)[0];
            mG = fromHex(mHex)[1];
            mB = fromHex(mHex)[2];

            mColorR.setProgress(mR);
            mColorG.setProgress(mG);
            mColorB.setProgress(mB);

        }



    }


    private static class SavedState extends BaseSavedState {
        // Member that holds the setting's value
        // Change this data type to match the type saved by your Preference
        String value;

        public SavedState(Parcelable superState) {
            super(superState);
        }

        public SavedState(Parcel source) {
            super(source);
            // Get the current preference's value
            value = source.readString();  // Change this to read the appropriate data type
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            super.writeToParcel(dest, flags);
            // Write the preference's value
            dest.writeString(value);  // Change this to write the appropriate data type
        }

        // Standard creator object using an instance of this class
        public static final Parcelable.Creator<SavedState> CREATOR =
                new Parcelable.Creator<SavedState>() {

                    public SavedState createFromParcel(Parcel in) {
                        return new SavedState(in);
                    }

                    public SavedState[] newArray(int size) {
                        return new SavedState[size];
                    }
                };
    }

}
